package cn.yedong.basic.interceptor;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.concurrent.TimeUnit;

/**
 * 拦截器
 */
@Component
public class LoginInterceptor implements HandlerInterceptor {
    @Autowired
    private RedisTemplate redisTemplate;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //获取请求头中的token
        String token = request.getHeader("token");
        System.out.println("token："+token);

        //校验token
        if(token != null){
            //从redis中查询token登陆信息
            Object obj = redisTemplate.opsForValue().get(token);
            //校验obj是否过期
            if(obj != null){
                //如果没有过期:刷新过期时间
                redisTemplate.opsForValue().set(token,obj,30, TimeUnit.MINUTES);
                //放行
                return true;
            }
        }

        //没有token，或redis登陆信息过期
        response.setContentType("application/json;charset=utf-8");
        //向前端传递登陆信息错误的JSON字符串，前端的前置拦截器进行判断和跳转页面
        response.getWriter().println("{\"success\":false,\"msg\":\"noLogin\"}");
        return false;
    }
}
